package by.msokoloff.javaweb2015.webapp.app;

import java.util.List;

import javax.inject.Inject;

import org.apache.wicket.Session;
import org.apache.wicket.authroles.authentication.AuthenticatedWebSession;
import org.apache.wicket.authroles.authorization.strategies.role.Roles;
import org.apache.wicket.injection.Injector;
import org.apache.wicket.request.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import by.msokoloff.javaweb2015.datamodel.AdmUser;
import by.msokoloff.javaweb2015.datamodel.AdmUser_;
import by.msokoloff.javaweb2015.services.AdmUserService;

public class BasicAuthenticationSession extends AuthenticatedWebSession {

    private static final Logger LOGGER = LoggerFactory.getLogger(BasicAuthenticationSession.class);

    private Integer userId;

    private Roles roles;

    @Inject
    private AdmUserService admUserService;

    public BasicAuthenticationSession(final Request request) {
        super(request);
        Injector.get().inject(this);
    }

    public static BasicAuthenticationSession get() {
        return (BasicAuthenticationSession) Session.get();
    }

    @Override
    public boolean authenticate(final String username, final String password) {
        boolean authenticationResult = false;
        List<AdmUser> users = admUserService.getByField(AdmUser_.login, username);
        if (users.size() == 1 && users.get(0).getPassword().equals(password)){
        	this.userId = users.get(0).getId();
        	LOGGER.debug("User authenticated");
        	authenticationResult = true;
        } else {
        	LOGGER.debug("Authentication failed!");
        }
        return authenticationResult;
    }

    @Override
    public Roles getRoles() {
        if (isSignedIn() && (roles == null)) {
            roles = new Roles();
            roles.add("SIGNED_IN");
            // TODO add real roles
            roles.add("ADMIN");
        }
        return roles;
    }

    @Override
    public void signOut() {
        super.signOut();
        userId = null;
    }

    public Integer getUserId() {
        return userId;
    }

}
